package svc

import (
	"cloud-entropy-storage-system/common/pkg/session"
	"cloud-entropy-storage-system/server/model/user"
	"encoding/json"
	"github.com/cilidm/toolbox/str"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

func IsSignedIn(c *gin.Context) bool {
	uid := session.Get(c, user.Uid)
	return uid != nil
}

// SignOut 用户注销
func SignOut(c *gin.Context) error {
	err := session.Del(c, user.Uid)
	if err != nil {
		return err
	}
	err = session.Del(c, user.SessionInfo)
	if err != nil {
		return err
	}
	return nil
}

// GetUserDetail 获得用户信息详情
func GetUserDetail(c *gin.Context) *user.User {
	tmp := session.Get(c, user.SessionInfo)
	if tmp == nil {
		return nil
	}
	u := new(user.User)
	if s, ok := tmp.(string); ok {
		err := json.Unmarshal([]byte(s), &u)
		if err != nil {
			return nil
		}
	}
	return u
}

func GetUserId(c *gin.Context) int {
	s := sessions.Default(c)
	uid := s.Get(user.Uid)
	if uid == nil {
		uid = 0
	}
	if val, ok := uid.(int); ok == true {
		return val
	}
	return 0
}

func NewPassword(len int, pwd string) (string, string) {
	salt := str.GetRandomString(len)
	defaultPwd := "123456"
	if pwd != "" {
		defaultPwd = pwd
	}
	return str.Md5([]byte(defaultPwd + salt)), salt
}
